# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community
Edition) available.
Copyright (C) 2017-2021 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://opensource.org/licenses/MIT
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.
"""

from django.db import models
from datetime import datetime

# Create your models here.

class Records(models.Model):
    PLATFORMS = [
        ("cmdb", "配置平台"),
        ("jobs", "作业平台"),
        ("monitor", "监控平台"),
        ("sops", "运维平台")
    ]
    OPER_METHOD = [
        ("POST", "新增"),
        ("DELETE", "删除"),
        ("PATCH", "修改")
    ]
    platform = models.CharField(verbose_name="平台", choices=PLATFORMS, max_length=10)
    oper_name = models.CharField(verbose_name="操作人", max_length=30)
    oper_ip = models.CharField(verbose_name="操作人IP", max_length=30)
    oper_datetime = models.DateTimeField(default=datetime.now(), verbose_name="操作时间")
    plat_module = models.CharField(verbose_name="操作模块", max_length=30)
    oper_method = models.CharField(verbose_name="操作方法", choices=OPER_METHOD, max_length=10)
    params = models.JSONField(null=True, verbose_name="请求参数")

    def save(self, request, params):
        x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')  # 判断是否使用代理
        if x_forwarded_for:
            ip = x_forwarded_for.split(',')[0]  # 使用代理获取真实的ip
        else:
            ip = request.META.get('REMOTE_ADDR')  # 未使用代理获取IP
        self.platform = "cmdb"
        self.oper_name = request.user.username
        self.oper_ip = ip
        self.plat_module = request.resolver_match.url_name
        self.oper_method = request.method
        self.params = params
        super().save()

class NameList(models.Model):
    name_list = models.JSONField(default={"black_bizs": [2, 3, 11, 12, 13], "white_bizs": []}, verbose_name="黑白名单")